package com.app.gamev2.ui.game

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Matrix
import android.graphics.Paint
import android.util.AttributeSet
import android.view.MotionEvent
import android.util.Log
import android.view.View
import androidx.core.content.ContextCompat
import com.app.gamev2.R
import com.app.gamev2.objects.Bucket
import com.app.gamev2.objects.Platform
import com.app.gamev2.objects.Player
import com.app.gamev2.game.GameManager

/**
 * 游戏视图类，负责绘制游戏元素和处理触摸事件
 */
class GameView(context: Context, attrs: AttributeSet?) : View(context, attrs) {
    // 画笔
    private val platformPaint = Paint()
    private val textPaint = Paint()
    
    // 平台图片资源
    private var cloudPlatformBitmap: Bitmap? = null
    private var cloudPlatformWithBucketBitmap: Bitmap? = null
    
    // 游戏管理器
    private lateinit var gameManager: GameManager
    
    // 玩家对象
    private lateinit var player: Player
    
    // 触摸开始时间（用于计算跳跃力度）
    private var touchStartTime = 0L
    
    // 是否正在触摸跳跃按钮
    private var isTouchingJumpButton = false

    init {
        // 初始化画笔
        platformPaint.color = ContextCompat.getColor(context, R.color.purple_500)
        platformPaint.style = Paint.Style.FILL
        
        textPaint.color = ContextCompat.getColor(context, R.color.black)
        textPaint.textSize = 30f
        textPaint.isAntiAlias = true
        
        // 初始化平台图片资源
        try {
            loadCloudPlatformBitmaps()
            // 验证图片是否成功加载
            if (cloudPlatformBitmap == null) {
                Log.e("GameView", "Failed to load cloud_platform bitmap")
            }
        } catch (e: Exception) {
            Log.e("GameView", "Error loading cloud platform bitmaps", e)
        }
    }

    /**
     * 设置游戏管理器
     */
    fun setGameManager(manager: GameManager) {
        this.gameManager = manager
    }

    /**
     * 设置玩家对象
     */
    fun setPlayer(player: Player) {
        this.player = player
    }

    /**
     * 绘制游戏元素
     */
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        // 绘制背景（可以实现渐变效果）
        drawBackground(canvas)

        // 绘制平台
        drawPlatforms(canvas)

        // 绘制氦气罐
        drawBuckets(canvas)

        // 绘制玩家
        drawPlayer(canvas)

        // 绘制调试信息（可选）
        drawDebugInfo(canvas)
    }

    /**
     * 绘制背景
     */
    private fun drawBackground(canvas: Canvas) {
        // 简单的纯色背景，实际游戏中可以实现渐变效果
        val backgroundPaint = Paint()
        backgroundPaint.color = ContextCompat.getColor(context, R.color.color_splash_bg)
        canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), backgroundPaint)
    }

    /**
     * 加载云朵平台的图片资源
     */
    private fun loadCloudPlatformBitmaps() {
        try {
            // 使用VectorDrawable的方式加载资源
            val vectorDrawable = resources.getDrawable(R.drawable.cloud_platform, null) as? android.graphics.drawable.VectorDrawable
            
            if (vectorDrawable != null) {
                Log.d("GameView", "Successfully loaded cloud_platform as VectorDrawable")
                
                // 创建一个足够大的Bitmap来容纳VectorDrawable
                val width = vectorDrawable.intrinsicWidth
                val height = vectorDrawable.intrinsicHeight
                
                if (width > 0 && height > 0) {
                    // 为普通平台创建Bitmap
                    cloudPlatformBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
                    val canvas = Canvas(cloudPlatformBitmap!!)
                    vectorDrawable.setBounds(0, 0, width, height)
                    vectorDrawable.draw(canvas)
                    
                    Log.d("GameView", "Successfully created cloud_platform bitmap with width: $width, height: $height")
                    
                    // 为带水桶的平台创建修改颜色的Bitmap
                    cloudPlatformWithBucketBitmap = cloudPlatformBitmap!!.copy(Bitmap.Config.ARGB_8888, true)
                    
                    // 修改带水桶的平台图片颜色
                    if (cloudPlatformWithBucketBitmap != null) {
                        val pixels = IntArray(cloudPlatformWithBucketBitmap!!.width * cloudPlatformWithBucketBitmap!!.height)
                        cloudPlatformWithBucketBitmap!!.getPixels(pixels, 0, cloudPlatformWithBucketBitmap!!.width, 0, 0, cloudPlatformWithBucketBitmap!!.width, cloudPlatformWithBucketBitmap!!.height)
                        
                        // 遍历所有像素，修改颜色为浅蓝色调
                        for (i in pixels.indices) {
                            val alpha = pixels[i] and 0xFF000000.toInt()
                            val red = pixels[i] and 0x00FF0000
                            val green = pixels[i] and 0x0000FF00
                            val blue = pixels[i] and 0x000000FF
                            
                            // 如果像素不是透明的，修改为浅蓝色调
                            if (alpha != 0) {
                                val newRed = (red * 0.7).toInt() and 0x00FF0000
                                val newGreen = (green * 0.9).toInt() and 0x0000FF00
                                val newBlue = (blue * 1.2).toInt() and 0x000000FF
                                pixels[i] = alpha or newRed or newGreen or newBlue
                            }
                        }
                        
                        cloudPlatformWithBucketBitmap!!.setPixels(pixels, 0, cloudPlatformWithBucketBitmap!!.width, 0, 0, cloudPlatformWithBucketBitmap!!.width, cloudPlatformWithBucketBitmap!!.height)
                        Log.d("GameView", "Successfully processed cloud platform with bucket bitmap")
                    }
                } else {
                    Log.e("GameView", "VectorDrawable has invalid intrinsic dimensions: width=$width, height=$height")
                }
            } else {
                Log.e("GameView", "Failed to load cloud_platform as VectorDrawable")
                // 如果VectorDrawable加载失败，回退到BitmapFactory方式
                cloudPlatformBitmap = BitmapFactory.decodeResource(resources, R.drawable.cloud_platform)
                if (cloudPlatformBitmap != null) {
                    Log.d("GameView", "Fallback to BitmapFactory successful with width: ${cloudPlatformBitmap!!.width}, height: ${cloudPlatformBitmap!!.height}")
                    // 创建带水桶的平台图片
                    cloudPlatformWithBucketBitmap = cloudPlatformBitmap!!.copy(Bitmap.Config.ARGB_8888, true)
                }
            }
        } catch (e: Exception) {
            Log.e("GameView", "Error loading cloud platform bitmaps", e)
        }
    }
    
    /**
     * 绘制平台
     */
    private fun drawPlatforms(canvas: Canvas) {
        val platforms = gameManager.getPlatforms()
        
        Log.d("GameView", "Number of platforms to draw: ${platforms.size}")
        
        // 检查图片资源状态
        Log.d("GameView", "Cloud platform bitmap status: ${if (cloudPlatformBitmap != null) "loaded" else "not loaded"}")
        Log.d("GameView", "Cloud platform with bucket bitmap status: ${if (cloudPlatformWithBucketBitmap != null) "loaded" else "not loaded"}")
        
        // 如果图片未加载或加载失败，尝试重新加载
        if (cloudPlatformBitmap == null) {
            try {
                loadCloudPlatformBitmaps()
                Log.d("GameView", "Attempted to reload cloud platform bitmaps")
            } catch (e: Exception) {
                Log.e("GameView", "Failed to reload cloud platform bitmaps", e)
            }
        }
        
        for (platform in platforms) {
            // 选择要使用的平台图片
            val bitmap = if (platform.hasBucket && cloudPlatformWithBucketBitmap != null) {
                cloudPlatformWithBucketBitmap
            } else {
                cloudPlatformBitmap
            }
            
            // 如果图片已加载，使用图片绘制平台
            if (bitmap != null) {
                // 使用Matrix缩放绘制代替每次创建新的Bitmap
                val matrix = Matrix()
                matrix.setScale(
                    platform.width / bitmap.width.toFloat(),
                    platform.height / bitmap.height.toFloat()
                )
                // 设置位置偏移
                matrix.postTranslate(platform.position.x, platform.position.y)
                
                // 绘制平台图片
                canvas.drawBitmap(
                    bitmap,
                    matrix,
                    null
                )
            } else {
                // 如果图片加载失败，回退到绘制矩形
                if (platform.hasBucket) {
                    platformPaint.color = ContextCompat.getColor(context, R.color.teal_700)
                } else {
                    platformPaint.color = ContextCompat.getColor(context, R.color.purple_500)
                }
                
                canvas.drawRect(
                    platform.position.x,
                    platform.position.y,
                    platform.position.x + platform.width,
                    platform.position.y + platform.height,
                    platformPaint
                )
            }
            
            // 如果平台正在消失，可以绘制特殊效果（例如透明度渐变）
            if (platform.isMarkedForRemoval) {
                // 这里可以实现消失动画效果
            }
        }
    }

    /**
     * 绘制氦气罐
     */
    private fun drawBuckets(canvas: Canvas) {
        val buckets = gameManager.getBuckets()
        
        for (bucket in buckets) {
            // 根据氦气罐等级设置不同颜色
            val bucketPaint = Paint()
            when (bucket.level) {
                1 -> bucketPaint.color = ContextCompat.getColor(context, R.color.teal_200) // 浅蓝色
                2 -> bucketPaint.color = ContextCompat.getColor(context, android.R.color.holo_blue_light) // 浅蓝绿色
                3 -> bucketPaint.color = ContextCompat.getColor(context, android.R.color.holo_green_light) // 浅绿色
                4 -> bucketPaint.color = ContextCompat.getColor(context, android.R.color.holo_orange_light) // 浅橙色
                5 -> bucketPaint.color = ContextCompat.getColor(context, android.R.color.holo_red_light) // 浅红色
                6 -> bucketPaint.color = ContextCompat.getColor(context, android.R.color.holo_purple) // 浅紫色
                7 -> bucketPaint.color = ContextCompat.getColor(context, R.color.purple_200) // 浅紫色
                8 -> bucketPaint.color = ContextCompat.getColor(context, android.R.color.holo_blue_light) // 浅蓝色
                9 -> bucketPaint.color = ContextCompat.getColor(context, android.R.color.holo_green_light) // 浅绿色
                10 -> bucketPaint.color = ContextCompat.getColor(context, android.R.color.holo_orange_light) // 浅橙色
                else -> bucketPaint.color = ContextCompat.getColor(context, R.color.teal_200) // 默认浅蓝色
            }
            
            // 应用合并动画效果
            if (bucket.isMerging) {
                // 设置透明度
                bucketPaint.alpha = (255 * bucket.getMergeAlpha()).toInt()
            }
            
            // 绘制氦气罐（简化为圆形）
            val radius = bucket.size / 2 * bucket.getMergeScale()
            canvas.drawCircle(bucket.position.x, bucket.position.y, radius, bucketPaint)
            
            // 绘制氦气罐等级文字
            textPaint.textSize = radius
            textPaint.textAlign = Paint.Align.CENTER
            canvas.drawText(
                "${bucket.level}",
                bucket.position.x,
                bucket.position.y + radius / 3,
                textPaint
            )
        }
    }

    // 随机颜色生成器
    private val random = java.util.Random()
    
    // 有活力的颜色数组（使用标准Android Holo颜色资源）
    private val vibrantColors = intArrayOf(
        android.R.color.holo_red_light,
        android.R.color.holo_orange_light,
        android.R.color.holo_green_dark,
        android.R.color.holo_green_light,
        android.R.color.holo_blue_light,
        android.R.color.holo_purple,
        android.R.color.holo_blue_dark
    )
    
    // 缓存每个等级对应的颜色，确保同一等级颜色一致
    private val levelColors = mutableMapOf<Int, Int>()
    
    /**
     * 获取指定等级的随机颜色
     */
    private fun getColorForLevel(level: Int): Int {
        // 如果该等级还没有分配颜色，则随机分配一个
        if (!levelColors.containsKey(level)) {
            val randomColorRes = vibrantColors[random.nextInt(vibrantColors.size)]
            levelColors[level] = ContextCompat.getColor(context, randomColorRes)
        }
        return levelColors[level] ?: ContextCompat.getColor(context, R.color.purple_700)
    }
    
    /**
     * 绘制玩家
     */
    private fun drawPlayer(canvas: Canvas) {
        // 获取玩家的ImageView
        val imageView = player.getImageView()
        
        // 如果ImageView存在，绘制其图片
        if (imageView.drawable != null) {
            // 保存当前画布状态
            canvas.save()
            
            // 移动画布到玩家位置的中心点
            canvas.translate(player.position.x, player.position.y)
            
            // 获取Drawable的宽度和高度
            val drawableWidth = imageView.drawable.intrinsicWidth.toFloat()
            val drawableHeight = imageView.drawable.intrinsicHeight.toFloat()
            
            // 计算缩放比例，进一步增加缩放因子使气球更大
            val scale = (player.size * 2.0f) / Math.max(drawableWidth, drawableHeight)
            
            // 缩放画布
            canvas.scale(scale, scale)
            
            // 绘制Drawable
            imageView.drawable.setBounds(
                (-drawableWidth / 2).toInt(),
                (-drawableHeight / 2).toInt(),
                (drawableWidth / 2).toInt(),
                (drawableHeight / 2).toInt()
            )
            
            imageView.drawable.draw(canvas)
            
            // 恢复画布状态
            canvas.restore()
        } else {
            // 如果图片加载失败，回退到绘制圆形
            val playerPaint = Paint()
            playerPaint.color = getColorForLevel(player.bucketLevel)
            
            canvas.drawCircle(
                player.position.x,
                player.position.y,
                player.size / 2,
                playerPaint
            )
        }
    }

    /**
     * 绘制调试信息
     */
    private fun drawDebugInfo(canvas: Canvas) {
        // 显示玩家位置和状态
        textPaint.textSize = 20f
        textPaint.textAlign = Paint.Align.LEFT
        textPaint.color = ContextCompat.getColor(context, R.color.black)
        
        canvas.drawText(
            "Player: x=${player.position.x.toInt()}, y=${player.position.y.toInt()}, level=${player.bucketLevel}",
            10f,
            30f,
            textPaint
        )
        
        canvas.drawText(
            "Jumping: ${player.isJumping}, VSpeed: ${player.verticalVelocity.toInt()}",
            10f,
            60f,
            textPaint
        )
    }

    /**
     * 处理触摸事件
     */
    override fun onTouchEvent(event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                // 记录触摸开始时间
                touchStartTime = System.currentTimeMillis()
                isTouchingJumpButton = true
                
                // 当气球在空中上升时，点击屏幕空白处使气球下落
                // 判断条件：气球正在跳跃中且垂直速度为负（上升中）
                if (player.isJumping && player.verticalVelocity < 0) {
                    // 设置一个较大的正垂直速度，使气球快速下落
                    player.verticalVelocity = 400f // 增加下落速度，使气球下落更快
                }
            }
            
            MotionEvent.ACTION_UP -> {
                // 计算触摸持续时间（跳跃力度）
                val touchDuration = System.currentTimeMillis() - touchStartTime
                
                // 根据触摸时长计算跳跃力度（限制最大力度）
                val jumpPower = minOf(touchDuration / 10f, 100f)
                
                // 触发跳跃
                player.jump(jumpPower)
                
                isTouchingJumpButton = false
            }
        }
        
        return true
    }

    /**
     * 更新游戏状态并重新绘制
     */
    fun updateAndInvalidate() {
        invalidate()
    }
}